package cc.ilzy.mall.user.service.impl;

import cc.ilzy.mall.user.config.OSSConfig;
import cc.ilzy.mall.user.service.IFileService;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements IFileService {
    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserHeaderImg(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        // 获取相关配置
        String endpoint = ossConfig.getEndpoint();
        String AccessKeyId = ossConfig.getAccessKeyId();
        String AccessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();

        // 这里可以使用阿里云OSS SDK进行文件上传
        OSS ossClient = new OSSClientBuilder().build(endpoint, AccessKeyId, AccessKeySecret);

        LocalDateTime now = LocalDateTime.now();
        String folder = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(now);

        String filename = UUID.randomUUID().toString();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = "images/" + folder + "/" + filename + extension;
        try {
            // 上传文件到OSS
            ossClient.putObject(bucketName, newFileName, file.getInputStream());
            log.info("File uploaded successfully: {}", newFileName);
            return "https://" + bucketName + "." + endpoint + "/" + newFileName;
        } catch (Exception e) {
            log.error("Error uploading file to OSS", e);
        } finally {
            ossClient.shutdown();
        }
        return null;
    }
}
